from PyQt5.QtCore import QObject, pyqtSignal  # 导入必要的类
import fitz  # PyMuPDF
import os

class PdfDocument(QObject):  # 继承QObject
    """PDF文档处理类，支持信号机制"""
    document_loaded = pyqtSignal()
    error_occurred = pyqtSignal(str)
    save_success = pyqtSignal(str)  # 新增：保存成功通知信号
    
    def __init__(self, parent=None):  # 添加父对象参数
        super().__init__(parent)  # 初始化QObject父类
        self._doc = None
        self._file_path = ""
        self._is_loaded = False
    
    @property
    def is_loaded(self):
        return self._is_loaded
    
    @property
    def file_path(self):
        return self._file_path
    
    def load(self, file_path):
        """加载PDF文件"""
        try:
            if not os.path.exists(file_path):
                self.error_occurred.emit(f"文件不存在: {file_path}")
                return False
                
            self._doc = fitz.open(file_path)
            self._file_path = file_path
            self._is_loaded = True
            self.document_loaded.emit()
            return True
        except Exception as e:
            self.error_occurred.emit(f"加载失败: {str(e)}")
            self._is_loaded = False
            return False
    
    def get_page_count(self):
        """获取总页数"""
        if self._doc:
            return len(self._doc)
        return 0
    
    def get_page(self, page_num):
        """获取指定页面"""
        if self._doc and 0 <= page_num < len(self._doc):
            return self._doc[page_num]
        return None
    
    def delete_page(self, page_num):
        """删除指定页面"""
        try:
            if not self._doc or page_num < 0 or page_num >= len(self._doc):
                return False
                
            self._doc.delete_page(page_num)
            return True
        except Exception as e:
            self.error_occurred.emit(f"删除页面失败: {str(e)}")
            return False
    
    def save(self, file_path=None, force_optimize=True):
        """保存PDF文件（优化版：清理冗余数据+压缩）
        Args:
            file_path: 保存路径（None则覆盖原文件）
            force_optimize: 是否强制优化（清理冗余+压缩）
        Returns:
            bool: 保存成功返回True，失败返回False
        """
        try:
            if not self._doc:
                self.error_occurred.emit("无打开的PDF文档，无法保存")
                return False
            
            # 确定保存路径
            save_path = file_path if file_path else self._file_path
            if not save_path:
                self.error_occurred.emit("保存路径为空")
                return False
            
            # 关键优化：配置PyMuPDF保存参数，彻底清理冗余
            save_options = {
                "incremental": False,  # 禁用增量保存（增量会保留历史数据）
                "garbage": 4,          # 深度清理冗余对象（1-4，4为最彻底）
                "deflate": True,       # 压缩页面流、字体等内容
                "clean": True,         # 清理无效的交叉引用表
                "expand": False        # 不展开压缩对象（避免体积增大）
            }
            
            # 根据优化开关应用参数
            if force_optimize:
                self._doc.save(save_path, **save_options)
            else:
                self._doc.save(save_path)  # 兼容原有默认保存逻辑
            
            self._file_path = save_path
            self.save_success.emit(f"已保存至：{save_path}（已优化文件体积）")
            return True
        
        except Exception as e:
            error_msg = f"保存失败：{str(e)}"
            self.error_occurred.emit(error_msg)
            return False
    
    def close(self):
        """关闭文档"""
        if self._doc:
            self._doc.close()
            self._doc = None
            self._is_loaded = False
            self._file_path = ""
